﻿#include "myserver.h"
#include "mainwindow.h"

MyServer::MyServer():QObject()
{
    connect(&server,SIGNAL(newConnection()),this,SLOT(incomingConnection()));
    memset(bReady,0,sizeof(bReady));
    timer=new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(onTimer()));
}

void MyServer::incomingConnection()
{
    qDebug()<<("incoming Connection");
    QTcpSocket * socket= server.nextPendingConnection();
    sockets.append(socket);
    connect(socket,SIGNAL(disconnected()),this,SLOT(socketDisconnected()));
    connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()));

}

bool MyServer::start()
{
    server.listen(QHostAddress::Any,42000);
    timer->start(200);
    qDebug()<<("server start");
    return true;
}

void MyServer::stop()
{
    if(server.isListening())
        server.close();
    qDebug()<<("server stop");
}

void MyServer::socketDisconnected()
{
    QTcpSocket * socket = qobject_cast<QTcpSocket *>(sender());
    int i=sockets.indexOf(socket);
    bReady[i]=false;
    sockets.removeAt(i);
    qDebug()<<"disconnected()";
}

void MyServer::readyRead()
{
    QTcpSocket * socket = qobject_cast<QTcpSocket *>(sender());
    int i=sockets.indexOf(socket);
    bReady[i]=true;
}

void MyServer::onTimer()
{
    for(int i=0;i<sockets.length();i++)
    {
        if(bReady[i])
        {
            bReady[i]=false;
            QByteArray ba=sockets[i]->readAll();
            QString str = QString::fromUtf8(ba);
            qDebug()<<str;
            sockets[i]->write("OK\n");
        }
    }
}

void MyServer::send(QString msg)
{
    msg = msg + "\n";
    QByteArray ba=msg.toUtf8();
    for(int i=0;i<sockets.length();i++)
    {
        sockets[i]->write(ba);
    }
}
